package org.babygo.connect.handler.client.msg;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.File;

import org.babygo.connect.NettyFileOperator;
import org.babygo.connect.protocol.GetAndSendFileRequest;
import org.babygo.connect.server.NettyService;
import org.babygo.connect.util.CommonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClientRequestInHandler  extends ChannelInboundHandlerAdapter{
	private Logger log = LoggerFactory.getLogger(ClientRequestInHandler.class);

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		log.info("收到来自服务器发送文件的请求");
		if (msg instanceof GetAndSendFileRequest){
			GetAndSendFileRequest req = (GetAndSendFileRequest) msg;
			log.info("传送文件的名称为:" + req.getFileName());
			String[] ipAndPort = CommonUtil.getIpAndPort(ctx.channel().remoteAddress());
			if (!NettyFileOperator.OPERTATOR.acceptPushFile(ipAndPort[0], req.getFileName())){
				log.info("拒绝接受对方发过来的文件");
				return;
			}
			String port = CommonUtil.getFixLenthString(4);
			log.info("提供了一个新端口给服务端:" + port);
			new NettyService(Integer.parseInt(port)).opernFileServer();
			ctx.writeAndFlush(new GetAndSendFileRequest(req.getFileName(), port));
		}
	}
}